<template>
<div>
  <q-select
    outlined
    v-model="selectArtist"
    use-input
    hide-selected
    fill-input
    map-options
    input-debounce="0"
    :options="artistOptions"
    @filter="onSearch"
    @input-value="setSelectedArtist"
    @update:model-value="onUpdatedModel"
    label="音乐人"
    hint="请输入音乐人名字进行检索"
    style="width: 250px;padding-bottom: 32px"></q-select>

</div>
</template>

<script setup>

import {ref,onMounted,computed} from 'vue'
import artistApi from '../api/artist.js'

const props=defineProps({
  artistList:{
    type:Array,
    default:()=>{
      return []
    }
  }

})

onMounted(()=>{
  if (props.artistList.length!==0){
    selectArtist.value=props.artistList[0].name
  }
})

const emit=defineEmits(['update:artistList'])

const onUpdatedModel=currentSelection=>{
  const result=artists.value.filter(item=>item.id===currentSelection.value)
  emit('update:artistList',result)
}
const artists=ref([])
const artistOptions=computed(()=>{
  return artists.value.map(item=>{
    return {value:item.id,label:item.name}
  })
})

const selectArtist=ref(null)
const lastSearch=ref('')
onMounted(()=>{
  artistApi.search({name:''}).then(res=>{
    artists.value=res.content
  })
})

const onSearch=(name,update,abort)=>{
  if (!selectArtist.value||lastSearch.value===selectArtist.value.label){
    update();
    return
  }
  update(()=>{
    lastSearch.value=selectArtist.value.label
    artistApi.search({name:selectArtist.value.label})
        .then(res=>{
          artists.value=res.content
        }).catch(()=>{
         abort() //可以停止检索动画
    })
})
}


const setSelectedArtist=value=>{
  selectArtist.value={label:value,value:null}
}
























</script>

<style scoped>

</style>